/**
 * Copyright @ 2023 iAuto (Shanghai) Co., Ltd.
 * All Rights Reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are NOT permitted except as agreed by
 * iAuto (Shanghai) Co., Ltd.
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 */

import React, { useEffect, useState } from 'react';
import { useReactive, useRequest } from 'ahooks';
import {
  Input,
  Row,
  Col,
  Select,
  Table,
  Button,
  Tabs,
  TableColumnsType,
  Image,
  message,
} from 'antd';
import IAutoPage from '@/components/soa/IAutoPage';
import styles from './index.less';
import { SearchOutlined } from '@ant-design/icons';
import {
  getCarCellPhone,
  getOneCarOneCellPhone,
  getOneCarOneGearSceneVehicleList,
} from '@/services/soa/oneCarOneGearScene';

import STable from './STable';
import { router } from 'umi';
import { IOneCarOneGearItem, IOneCarOneGearTabEnum } from '@/types/oneCarOneGearScene';
import DrawerAbilityDetail from '../abilitymanagement/DrawerAbilityDetail';
import ServiceDetailsDrawer from '../serviceManage/servicePublishing/ServiceDetailsDrawer';
import { abilityItem } from '@/types/ability';
import { connect } from 'dva';
import { getDateTime } from '@/utils/soa/utils';
import MaskText from '@/components/MaskText';
// import {sceneAuditDetail} from "@/services/soa/sceneAudit";
// import IAutoTableButton from '@/components/soa/IAutoTableButton';

const { Option } = Select;

const Index: React.FC<any> = ({ dispatch, menu }) => {
  const [carRecord, setCarRecord] = useState<any>(null);
  const [selectedRowKeys, setSelectedRowKeys] = useState<string[]>([]);
  const [detailInfo, setDetailInfo] = useState<any>({ id: null });
  const [showDetail, setShowDetail] = useState(false);
  const [leftTableData, setLeftTableData] = React.useState<any>([]);
  // 服务列表item
  const [serveItem, setServeItem] = React.useState<any>({});
  const [serveItemDrawer, setServeItemDrawer] = React.useState(false);
  const state = useReactive<{
    type: number;
    content: string;
  }>({
    type: 0,
    content: '',
  });

  const mobileObj = useReactive<Record<string, string>>({});

  const visible = useReactive<Record<string, boolean>>({});
  const carResponse = useRequest(getOneCarOneGearSceneVehicleList, {
    manual: true,
    onSuccess: (res, params) => {
      setLeftTableData(res?.data?.dataList);
    },
    // defaultParams: [{ fuzzyField:""}],
  });
  const oneCarOneCellPhone = useRequest(getOneCarOneCellPhone, {
    manual: true,
    onSuccess: (res, params) => {
      setLeftTableData(res?.data);
    },
  });
  const [carMap, setCarMap] = useState<any>({});

  const carCellPhone = useRequest(getCarCellPhone, {
    manual: true,
    onSuccess: (res, params) => {
      mobileObj[params[0]] = res?.data?.mobile;
    },
  });
  const oneCarCellPhone = (
    text: any,
    record: any,
    event: React.MouseEvent<HTMLAnchorElement, MouseEvent>,
  ) => {
    event.stopPropagation();
    carCellPhone.run(record?.vin);
    visible[record.vin] = true;
  };

  useEffect(() => {
    if (dispatch) {
      dispatch({
        type: 'abilityModel/getAbilityPublishDetail',
      }).then((res: any) => {
        console.log('🚀 ~ file: index.tsx ~ line 68 ~ useEffect ~ res', res);
        setCarMap(res.data.allCarModelMap);
      });
    }
  }, []);

  // 查看详情
  const handleToSoaDetail = (record: abilityItem) => {
    setDetailInfo({ id: record.skillVersionId, skillName: record.name });
    setShowDetail(true);
  };

  const columns: TableColumnsType<IOneCarOneGearItem> = [
    {
      title: '车辆VIN',
      dataIndex: 'vin',
      // width:180,
      width: '32%',
    },
    {
      title: '车系',
      dataIndex: 'seriesName',
      // width:140,
      width: '12%',
      render: (text, record) => {
        return (
          // <span>{record?.seriesName+"/"+record?.modelName}</span>
          <div>
            <span>{record?.seriesName}</span>
          </div>
        );
      },
    },
    {
      title: '车型',
      dataIndex: state.type === 0 ? 'modelName' : 'typeName',
      // width:140,
      width: '22%',
      render: (text, record) => {
        return (
          // <span>{record?.seriesName+"/"+record?.modelName}</span>
          <div>
            <span>{state.type === 0 ? record?.modelName : record?.typeName}</span>
          </div>
        );
      },
    },
    // {
    //   title: '车型',
    //   dataIndex:state.type === 0 ?'modelName':'typeName',
    // },
    {
      title: '手机号',
      dataIndex: 'cellPhone',
      // width:180,
      width: '34%',
      // render: (text, record) => {
      //   return (
      //     <div>
      //       {visible[record.vin] ? text : <a onClick={() => (visible[record.vin] = true)}>查看</a>}
      //     </div>
      //   );
      // },
      render: (text, record) => {
        return (
          <div>
            {/*{carCellPhone?.data?.data?.mobile.replace(text.substring(3,11),"********")}*/}
            {visible[record.vin] ? (
              <MaskText text={mobileObj[record.vin]} type="phone" />
            ) : (
              <a onClick={event => oneCarCellPhone(text, record, event)}>查看</a>
            )}
          </div>
        );
      },
    },
  ];

  const carChange = (value: any) => {
    state.type = value;
    state.content = '';
    if (value == 1) {
      carResponse.mutate(undefined);
    } else if (value == 0) {
      oneCarOneCellPhone.mutate(undefined);
    }
  };

  /**
   * @description 搜索
   */
  const onSearch = () => {
    if (state.content.length < 6) {
      message.error('请至少输入6位VIN码或者手机号');
      return;
    }
    // vin
    // if (state.type === 0 && state.content.length >= 6) {
    if (state.type === 0 && state.content.length >= 6) {
      carResponse.run({ fuzzyField: state.content });
    } else if (state.type === 0 && state.content.length == 0) {
      message.error('请输入VIN码');
      carResponse.mutate(undefined);
    }

    // 电话
    if (state.type === 1 && state.content.length == 11) {
      oneCarOneCellPhone.run(state.content);
    } else if (state.type === 1 && state.content.length == 0) {
      message.error('请输入手机号');
      oneCarOneCellPhone.mutate(undefined);
    }
  };

  /**
   * @description 搜索
   */
  const onRowClick = (record: IOneCarOneGearItem) => {
    setCarRecord(record);
  };

  const getVal = (str: string | number) => {
    if (typeof str == 'string') {
      return Number(str.split('.').join(''));
    } else if (typeof str == 'number') {
      return str;
    } else {
      return str;
    }
  };

  const items = [
    {
      label: '服务',
      id: 1,
      url: IOneCarOneGearTabEnum[1],
      columns: [
        {
          title: '服务ID',
          dataIndex: 'serviceId',
        },
        {
          title: '服务名称',
          dataIndex: 'name',
        },
        {
          title: '服务矩阵版本号',
          dataIndex: 'socVersion',
          defaultSortOrder: 'ascend',
        },
        {
          title: '操作',
          key: 'action',
          render: (_, record) => (
            <Button
              type="primary"
              ghost
              onClick={() => {
                setServeItem(record);
                setServeItemDrawer(true);
              }}
            >
              查看
            </Button>
          ),
        },
      ],
      rowKey: 'serviceId',
    },
    {
      label: '能力',
      id: 2,
      url: IOneCarOneGearTabEnum[2],
      columns: [
        {
          title: '能力名称',
          dataIndex: 'name',
        },
        {
          title: '能力ID',
          dataIndex: 'skillId',
        },
        {
          title: '分类',
          dataIndex: 'category',
        },
        {
          title: '能力类型',
          dataIndex: 'type',
          render: (tname: string) => {
            if (tname && tname != '0') {
              return '条件';
            } else {
              return '动作';
            }
          },
        },
        {
          title: '服务矩阵版本号',
          dataIndex: 'socVersion',
          defaultSortOrder: 'ascend',
        },
        {
          title: '操作',
          key: 'action',
          render: (_, record) => (
            <Button type="primary" ghost onClick={() => handleToSoaDetail(record)}>
              查看
            </Button>
          ),
        },
      ],
      rowKey: 'skillId',
    },
    {
      label: '场景',
      id: 3,
      url: IOneCarOneGearTabEnum[3],
      columns: [
        {
          title: '场景名',
          dataIndex: 'name',
        },
        {
          title: '图标',
          dataIndex: 'iconUrl',
          render: text => <Image src={text} preview={false} className={styles.icon} />,
        },
        {
          title: '服务矩阵版本号',
          dataIndex: 'serviceMatrixVersion',
          defaultSortOrder: 'ascend',
          sorter: (a, b) => getVal(a.serviceMatrixVersion) - getVal(b.serviceMatrixVersion),
        },
        {
          title: '更新人',
          dataIndex: 'updateNickName',
        },
        {
          title: '更新时间',
          dataIndex: 'updateTime',
          render: text => getDateTime(text),
        },
        {
          title: '操作',
          key: 'action',
          render: (_, record) => (
            <Button
              size={'small'}
              type="primary"
              ghost
              onClick={() => {
                router.push('/soaManage/oneCarOneGear/detailScene?sceneUuid=' + record.sceneUuid);
              }}
            >
              查看
            </Button>
          ),
        },
      ],
      rowKey: 'sceneUuid',
    },
  ];
  return (
    <Row>
      <Col span={9}>
        <IAutoPage>
          <Row>
            <Col span={24}>
              <Input.Group compact>
                <Select defaultValue={0} onChange={carChange}>
                  <Option value={0}>VIN码</Option>
                  <Option value={1}>手机号</Option>
                </Select>
                <Input
                  maxLength={20}
                  className={styles.width70}
                  suffix={<SearchOutlined onClick={onSearch} />}
                  allowClear
                  placeholder={state.type === 0 ? '输入VIN码进行搜索' : '输入手机号进行搜索'}
                  value={state.content}
                  onChange={e => (state.content = e.target.value)}
                  onPressEnter={onSearch}
                />
              </Input.Group>
            </Col>
            <Col span={24}>
              <Row justify={'start'}>
                <Col>
                  <span>*搜索结果最多显示前15条数据</span>
                </Col>
              </Row>
            </Col>
          </Row>

          <Row className={styles.marginTop8}>
            <Col span={24}>
              <div className={styles.tableBase}>
                <Table
                  tableLayout={'fixed'}
                  columns={columns}
                  dataSource={leftTableData}
                  pagination={false}
                  rowSelection={{
                    selectedRowKeys,
                    type: 'radio',
                    renderCell: () => '',
                    columnWidth: 0,
                  }}
                  rowKey={'vin'}
                  onRow={record => {
                    return {
                      // eslint-disable-next-line
                      onClick: e => {
                        onRowClick(record);
                        setSelectedRowKeys([record.vin]);
                      },
                    };
                  }}
                />
              </div>
            </Col>
          </Row>
        </IAutoPage>
      </Col>
      <Col span={15}>
        <IAutoPage>
          <div>
            <div>VIN：{carRecord?.vin}</div>
            <div>
              {carRecord?.brandName} {carRecord?.seriesName} {carRecord?.modelName}
            </div>
          </div>
          <Tabs type="card">
            {items.map(item => (
              <Tabs.TabPane tab={item.label} key={item.id}>
                <STable
                  menu={menu}
                  vin={carRecord?.vin}
                  url={item.url}
                  columns={item.columns}
                  rowKey={item.rowKey}
                />
              </Tabs.TabPane>
            ))}
          </Tabs>
        </IAutoPage>
      </Col>
      <DrawerAbilityDetail
        // showNext
        query={detailInfo}
        setShowDetail={setShowDetail}
        showDetail={showDetail}
      />
      <ServiceDetailsDrawer
        itemRow={serveItem}
        carMap={carMap}
        itemRowDrawer={serveItemDrawer}
        setItemRowDrawer={setServeItemDrawer}
      />
    </Row>
  );
};
export default connect(
  ({ abilityModel, menu, loading }: { abilityModel: any; menu: any; loading: any }) => ({
    abilityModel,
    menu,
    loading: loading.models.abilityModel,
  }),
)(Index);
